﻿using BaseUI;
using BLL;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace Thksoft.Funds
{
    public partial class PlanMonthFunds1 : BasePage
    {
        private Qs_SequencesBLL seqBll = new Qs_SequencesBLL();

        private IPlanMonthApply planMonthApply = new QS_PLANMONTHAPPLYBLL();
        private int Selectnum = -1;
        private static int isPB = 7;
        private static DataTable dtISPB = null;

        /// <summary>
        /// 判断是否首次加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("YearNum", Type.GetType("System.String"));
                dt.Columns.Add("Year", Type.GetType("System.String"));
                object[] parm = new object[2];
                int ye = Convert.ToInt32(DateTime.Now.AddYears(-5).Year.ToString());
                for (int i = ye; i <= Convert.ToInt32(DateTime.Now.AddYears(1).Year.ToString()); i++)
                {
                    parm[0] = i;
                    parm[1] = i + "";
                    dt.Rows.Add(parm);
                }
                DropDownList1.DataSource = dt;
                DropDownList1.DataValueField = "YearNum";
                DropDownList1.DataTextField = "Year";
                DropDownList1.DataBind();
                DropDownList1.SelectedValue = DateTime.Now.Year.ToString();

                DropDownList2.SelectedValue = DateTime.Now.Month.ToString();
                //   Response.Write(getWeek());
                BindInit(DateTime.Now.Year.ToString());
            }
        }

        /// <summary>
        /// 绑定加载数据
        /// </summary>
        public void BindInit(string yearStr)
        {
            var year = Convert.ToInt32(yearStr);
            var dt1 = (DataTable)planMonthApply.GetData((int)lognUser.USER_COMPANY, year).Data;
            gvMonthPlan.DataSource = dt1;
            gvMonthPlan.DataBind();
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            string year = DropDownList1.SelectedValue;
            string month = DropDownList2.SelectedValue;

            if (txtremark.Text.Trim() == "")
            {
                MessageBox.Show(Page, "请输入编制依据");
                return;
            }

            string whr = @" and t.N_BUSINESS_STATE =2  and t.n_year = " + year + @" and t.n_company_id =" + lognUser.USER_COMPANY.ToString();
            DataTable dt = new QX_PLANYEARAPPLYBLL().BindBussBy(whr, lognUser.USER_NAME);
            //判断是否已申请年计划
            if (dt != null && dt.Rows.Count > 0)
            {
            }
            else
            {
                MessageBox.Show(Page, "未申请年计划！");
                return;
            }

            string whr2 = @" and N_BUSINESS_STATE <>0  and t.n_year = " + year + @" and N_MONTH=" + month + @" and t.n_company_id =" + lognUser.USER_COMPANY.ToString();

            DataTable dt2 = new QS_PLANMONTHAPPLYBLL().GetSeleDataBind(whr2, lognUser.USER_NAME);

            if (dt2 != null && dt2.Rows.Count > 0)
            {
                string state = dt2.Rows[0]["N_BUSINESS_STATE"].ToString();

                if (state == "1")
                {
                    MessageBox.Show(Page, "已申请" + year + month.PadLeft(2, '0') + "月计划，流程正在流转中！");
                    return;
                }
                else if (state == "2")
                {
                    MessageBox.Show(Page, "已申请" + year + month.PadLeft(2, '0') + "月计划，并且流程已归档！");
                    return;
                }
            }

            Sum();

            decimal bid = new Qs_BusinessBLL().GetYearDid("seq_business_id");

            Sys_Company cModel = new Sys_CompanyBLL().GetInfoById(lognUser.USER_COMPANY.ToString());

            QS_Business bModel = new QS_Business();

            bModel.Business_Id = bid;
            bModel.Business_Name = year + month.PadLeft(2, '0') + "月计划编制（" + cModel.CMY_NAME + "）";
            bModel.Process_id = 51;
            bModel.Business_State = 1;
            bModel.Business_operator_Id = int.Parse(lognUser.USER_ID.ToString());
            bModel.Business_remark = txtremark.Text.Trim();
            bModel.N_COMPANY_ID = lognUser.USER_COMPANY;

            QS_PLANMONTHAPPLY yModel = new QS_PLANMONTHAPPLY();
            yModel.N_MONTHAPP_ID = new Qs_BusinessBLL().GetYearDid("SEQ_MONTHAPP_ID");
            yModel.N_YEAR = decimal.Parse(year);
            yModel.N_MONTH = decimal.Parse(month);
            yModel.C_USEMONTH = year + month.PadLeft(2, '0');

            yModel.N_BUSINESS_ID = bid;

            yModel.C_MONTH_NAME = year.ToString() + month.PadLeft(2, '0') + "（" + cModel.CMY_NAME + "）";

            yModel.N_COMPANY_ID = lognUser.USER_COMPANY;
            yModel.N_USER_ID = lognUser.USER_ID;
            yModel.C_REAMRK = txtremark.Text.Trim();
            yModel.N_BUSINESS_STATE = 1;
            yModel.N_YEARAPP_ID = decimal.Parse(dt.Rows[0]["N_YEARAPP_ID"].ToString());

            // DataTable dt = (DataTable)gvMonthPlan.DataSource;

            List<QS_PLANMONTH_DETAIL> list = new List<QS_PLANMONTH_DETAIL>();
            for (int i = 0; i < gvMonthPlan.Rows.Count; i++)
            {
                QS_PLANMONTH_DETAIL ydModel = new QS_PLANMONTH_DETAIL();
                string type = ((Label)gvMonthPlan.Rows[i].Cells[0].FindControl("lbltype")).Text;
                string pid = ((Label)gvMonthPlan.Rows[i].Cells[0].FindControl("lblProID")).Text;
                string xmmc = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("txtProjectName")).Text;

                string je = ((TextBox)gvMonthPlan.Rows[i].Cells[2].FindControl("txtNowMonth")).Text;
                string aa = "";
                if (je != "" && je != null)
                {
                    aa = FormulaCalculator.Eval(je).ToString();
                }

                string bz = ((TextBox)gvMonthPlan.Rows[i].Cells[3].FindControl("txtremark")).Text;

                string syje = ((Label)gvMonthPlan.Rows[i].Cells[2].FindControl("lblSyjh")).Text;

                ydModel.N_MONTHAPP_ID = yModel.N_MONTHAPP_ID;

                ydModel.N_PROID = decimal.Parse(pid);
                ydModel.C_PRONAME = xmmc;

                ydModel.N_AMOUNT = aa == "" ? 0 : Convert.ToDecimal(aa);//decimal.Parse(aa);

                ydModel.C_REMARK = bz;
                ydModel.N_OPERATORID = lognUser.USER_ID;

                ydModel.N_BUSINESS_ID = bid;
                ydModel.N_TYPE = Convert.ToDecimal(type);//decimal.Parse(type);

                ydModel.N_SYAMOUNT = Convert.ToDecimal(syje);//decimal.Parse(syje);

                ydModel.N_USEAMOUNT = 0;

                list.Add(ydModel);
            }

            Lc_Transaction tModel = new Lc_Transaction();
            tModel.N_PROCESS_ID = bModel.Process_id;

            tModel.N_QUEUE_ID = 142;
            tModel.N_business_id = bid;
            tModel.N_TRANSACTION_STATE = 1;
            tModel.C_TRANSACTION_COMMENT = "月计划申请";
            tModel.C_TRANSACTOR_ID = lognUser.USER_ID.ToString();
            tModel.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
            tModel.D_TRANSACTION_TIME_END = DateTime.Now;
            tModel.D_TRANSACTION_TIME_DUE = DateTime.Parse("1900-1-1");
            tModel.N_TRANSACTION_STATE = 1;

            tModel.C_TRANSACTOR_SIGNATURE = "";
            tModel.N_LAST_BACE_TRANSACTION_ID = 0;

            Lc_Transaction NexModel = new Lc_Transaction();
            NexModel.N_PROCESS_ID = bModel.Process_id;

            NexModel.N_QUEUE_ID = decimal.Parse(new Lc_ConditionBLL().GetNextNum(bModel.Process_id, tModel.N_QUEUE_ID).Rows[0][0].ToString());
            NexModel.N_business_id = bid;
            NexModel.N_TRANSACTION_STATE = 0;
            NexModel.C_TRANSACTION_COMMENT = "";
            NexModel.C_TRANSACTOR_ID = "";
            NexModel.D_TRANSACTION_TIME_BEGIN = DateTime.Now;
            NexModel.D_TRANSACTION_TIME_END = DateTime.Parse("1900-1-1");
            Lc_Queue qModel = new Lc_QueueBLL().GetInfoById(NexModel.N_QUEUE_ID.ToString());
            Lc_Node nModel = new Lc_NodeBLL().GetInfoById(qModel.N_NODE_ID.ToString());
            NexModel.D_TRANSACTION_TIME_DUE = DateTime.Now.AddDays(double.Parse(nModel.N_DOIING_TIME.ToString()));
            NexModel.N_TRANSACTION_STATE = 0;
            NexModel.C_TRANSACTOR_SIGNATURE = "";
            NexModel.N_LAST_BACE_TRANSACTION_ID = 0;

            int count = new QS_PLANMONTHAPPLYBLL().AppPlanMonth(bModel, yModel, list, tModel, NexModel, lognUser.USER_NAME);

            if (count > 0)
            {
                MessageBox.Show(Page, "申请成功！");
            }
            else
            {
                MessageBox.Show(Page, "申请失败！");
            }
        }

        protected void gvMonthPlan_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "cu=this.style.backgroundColor;this.style.backgroundColor='#d5e7ff'");
                e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor=cu");

                ((CheckBox)this.gvMonthPlan.Rows[e.Row.RowIndex].FindControl("chkSelectDel")).Checked = true;
            }
        }

        protected void btnSum_Click(object sender, EventArgs e)
        {
            Sum();
        }

        #region 求和 方法

        /// <summary>
        /// 求和
        /// </summary>
        private void Sum()
        {
            #region for循环求和

            try
            {
                DataTable dt = (DataTable)gvMonthPlan.DataSource;

                for (int i = 0; i < gvMonthPlan.Rows.Count; i++)
                {
                    //0 主节点  1分节点  2子节点（可录入数据）
                    string type = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("lbltype")).Text;
                    string pid = ((Label)gvMonthPlan.Rows[i].Cells[1].FindControl("lblProID")).Text;
                    if (type != "2")
                    {
                        //求和
                        decimal heje = 0;
                        //该节点下所有子节点
                        DataTable dtchild = new QS_PROJECTBLL().SelectFor(" and  d.n_type = 2 ", pid, lognUser.USER_NAME);

                        for (int j = 0; j < dtchild.Rows.Count; j++)
                        {
                            for (int k = 0; k < gvMonthPlan.Rows.Count; k++)
                            {
                                string type2 = ((Label)gvMonthPlan.Rows[k].Cells[1].FindControl("lbltype")).Text;

                                string pid2 = ((Label)gvMonthPlan.Rows[k].Cells[1].FindControl("lblProID")).Text;

                                //每个文本框求和
                                string je = ((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim();
                                string a = "";
                                if (je != "" && je != null)
                                {
                                    a = FormulaCalculator.Eval(je).ToString();
                                }

                                if (type2 == "2" && dtchild.Rows[j]["n_proid"].ToString() == pid2)
                                {
                                    heje += Convert.ToDecimal(a == "" ? "0" : a);
                                    //heje += Convert.ToDecimal(((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim() == "" ? "0" : ((TextBox)gvMonthPlan.Rows[k].Cells[2].FindControl("txtNowMonth")).Text.Trim());
                                }
                            }
                        }

                        ((Label)gvMonthPlan.Rows[i].Cells[2].FindControl("lblMonthjh")).Text = heje.ToString();
                        ((TextBox)gvMonthPlan.Rows[i].Cells[2].FindControl("txtNowMonth")).Text = heje.ToString();
                    }
                    else
                    {
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(Page, ex.Message);
                return;
            }

            #endregion for循环求和
        }

        #endregion 求和 方法

        protected void gvMonthPlan_RowDataBound1(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string sss = ((Label)e.Row.FindControl("lblProID")).Text;
                e.Row.Attributes.Add("onmouseover", "document.getElementById(\"p_id\").value=\"\"");
                e.Row.Attributes.Add("onmouseout", "document.getElementById(\"p_id\").value=\"" + ((Label)e.Row.FindControl("lblProID")).Text + "\";");
                e.Row.Cells[2].Attributes["style"] = "cursor:hand";
                string s = ((Label)e.Row.FindControl("lblFatherId")).Text;
                e.Row.Cells[2].Attributes["onContextMenu"] = "YouJian()";
                e.Row.Cells[1].Attributes["onContextMenu"] = "YouJian()";

                string type = ((Label)e.Row.FindControl("lbltype")).Text;
                if (type == "0")
                {
                    e.Row.Attributes["style"] = "background-color:#B2D8FF;font-size:14px";
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Enabled = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;
                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;
                }
                else if (type == "1")
                {
                    e.Row.Attributes["style"] = "background-color:#CCCCCC;font-size:13px";
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Visible = false;
                    ((TextBox)e.Row.FindControl("txtNowMonth")).Enabled = false;
                    ((Label)e.Row.FindControl("lblMonthjh")).Visible = true;
                    ((TextBox)e.Row.FindControl("txtremark")).Visible = false;
                    ((Label)e.Row.FindControl("lblreMark")).Visible = true;
                }
            }
        }

        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string year = DropDownList1.SelectedValue;
            BindInit(year);
        }
    }
}